package com.lagou.sqlSession;

import com.lagou.config.XMLConfigBuilder;
import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import org.dom4j.DocumentException;

import java.beans.PropertyVetoException;
import java.io.InputStream;

/**
 * @author: liufh
 * @create: 2021-06-27 22:21
 **/
public class SqlSessionFactoryBuilder {

    public SqlSessionFactory build(InputStream inputStream) throws DocumentException, PropertyVetoException {
        //使用dom4j解析配置文件，将解析出来的内容封装到Configuration中
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration = xmlConfigBuilder.loadXmlConfig(inputStream);
        //创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);

        return sqlSessionFactory;
    }

    /**
     * 测试直接将路径传入SqlSessionFactoryBuilder().build()，框架根据地址获取流
     * 调用方不再需获取流
     */
    public SqlSessionFactory build2(String path) throws DocumentException, PropertyVetoException {
        InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
        //使用dom4j解析配置文件，将解析出来的内容封装到Configuration中
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration = xmlConfigBuilder.loadXmlConfig(resourceAsStream);
        //创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);

        return sqlSessionFactory;
    }

}
